//
//  UIApplication+Extension.swift
//  8btc
//
//  Created by Steven Xie on 2018/11/15.
//  Copyright © 2018 Hangzhou Shichuo Information Technology Co, Ltd. All rights reserved.
//

import UIKit

public extension UIApplication {
    func openCustomURL(_ url: URL) {
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url)
        } else {
            UIApplication.shared.openURL(url)
        }
    }

    func fetchMainViewController<T: UIViewController>(type _: T.Type) -> T? {
        var root: T?
        UIApplication.shared.windows.forEach { window in
            if let rootVC = window.rootViewController as? T {
                root = rootVC
            }
        }

        return root
    }
    
    
    /// 获取导航栏
    func currentNavigationController() -> UINavigationController? {
        var parent: UIViewController?
        if let window = delegate?.window, let rootVC = window?.rootViewController {
            parent = rootVC
            while parent?.presentedViewController != nil {
                parent = parent?.presentedViewController!
            }

            if let tabbar = parent as? UITabBarController, let nav = tabbar.selectedViewController as? UINavigationController {
                return nav
            } else if let nav = parent as? UINavigationController {
                return nav
            }
        }
        return nil
    }
}
